package br.com.sgs.dao;

import br.com.sgs.entity.Funcionario;
import br.com.sgs.entity.Instituicao;
import br.com.sgs.entity.Usuario;
import br.com.sgs.util.UtilHibernate;
import java.sql.SQLException;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class AbstractDAO implements IDAO {

    EntityManager em;

    public AbstractDAO() {
        em = UtilHibernate.getEM();
    }

    @Override
    public void incluir (Object o) throws ClassNotFoundException, SQLException, Exception {
        try {

            em = UtilHibernate.getEM();
            em.getTransaction().begin();
            em.persist(o);
            em.getTransaction().commit();

        } catch (EntityExistsException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
        }

    }

    @Override
    public void alterar(Object o) throws ClassNotFoundException, SQLException, Exception {
        try {

            em = UtilHibernate.getEM();
            em.getTransaction().begin();
            em.merge(o);
            em.getTransaction().commit();

        } catch (EntityExistsException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
        }

    }

    @Override
    public void excluir(Object o) throws ClassNotFoundException, SQLException, Exception {
        try {

            em = UtilHibernate.getEM();
            em.getTransaction().begin();
            em.remove(o);
            em.getTransaction().commit();

        } catch (EntityExistsException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
        }

    }

}
